<?php
class Model_Authentication{

	private $_salt = '88L3W4USKab8GcpR';
	
	public function __construct(){
		
	}
	
	public function encrypt($password) {
		return md5($password.'-'.sha1($this->_salt));
	}
	
	public function isLoggued(){
		// on va regarder si l'utilisateur est authentifié
	 	$auth = Zend_Auth::getInstance();
        $identity = Zend_Auth::getInstance()->getIdentity();
        if($auth->hasIdentity()) {
        	// check token availability
        	$sM = new Model_Session();
        	$filter = array('id_user' => $identity['id']);
        	$session = $sM->get($filter);
        	// deconnexion if session limit is reach
        	if(isset($session[0]) and !is_null($session[0])) {
	        	$diff = Model_Tools::date_to_timestamp(date('Y-m-d H:i:m', time())) - Model_Tools::date_to_timestamp($session[0]['date']);
	        	$diff = floor($diff / 60);
	        	if($diff >= 20) {
	        		Model_Authentication::logout();
	        		$auth = Zend_Auth::getInstance();
	        	}
        	} else {
        		Model_Authentication::logout();
	       		$auth = Zend_Auth::getInstance();
        	}
        }
        return $auth->hasIdentity();
	}
	
	public function getlogguedInformations(){
		$auth = Zend_Auth::getInstance();
        return Zend_Auth::getInstance()->getIdentity();
	}
	
	public function logout(){
		$auth = Zend_Auth::getInstance();
        $identity = Zend_Auth::getInstance()->getIdentity();
		$auth->getStorage()->clear();
		// delete session
		$sM = new Model_Session();
		$where = array('id_user' => $identity['id']);
		$sM->del($where);
	}
	
	public function authenticate($email, $password){
	
		$uM = new Model_User();
		$filter = array('email' => $email,
						'password' => Model_Authentication::encrypt($password)
						);
		$user = $uM->get($filter);
		
		if(!empty($user)) {
			// get user's groups
			$ugM = new Model_UserGroup();
			$filter = array('id_user' => $user[0]['id']);
			$order = 'keyname';
			$groups = $ugM->get($filter);
			
			// if no group, not logged
			if(empty($groups)) {
				return false;
			}
			
			foreach($groups as $g) {
				$user[0]['groups'][] = $g['keyname'];
			}
			
			// add session
			// generate token
			$sM = new Model_Session();
			$token = Model_Authentication::encrypt(microtime());
			$datas = array('id_user' => $user[0]['id'],
							'token' => $token,
							'date' => DATE('Y-m-d H:i:s', time()));
			// check if session exist
			$filter = array('id_user' => $user[0]['id']);
			$session = $sM->get($filter);
			// if exist, update session
			if(isset($session[0])) {
				$sM->set($user[0]['id'], $datas);
			// if not exist, add session
			} else {
				$sM->add($datas);
			}
			
			$user[0]['token'] = $token;
			
			// store in registry
			$auth = Zend_Auth::getInstance();
			$auth->getStorage()->write($user[0]);
			return true;
			
		} else {
			return false;
		}
	}
}
?>
